<template>
  <div class="home">
    <div class="title">
      <div class="home-title">受限空间安全监测</div>
      <div class="home-label">
        <div class="home-label-netwall">
          <div v-for="(item, index) in this.$store.state.ipMacData.other" :key="index">
            网关{{item.netid}} <div class="home-light" :style='{background: item.online ?"#afffaf":"yellow"}'></div>
          </div>
        </div>
        <div v-if='this.iperror'>本机IP或者端口号错误</div>
        <div>当前时间：{{this.getCuTime()}}</div>
      </div>
    </div>
    <div class="gas-detector">
      <div v-for="(item, index) in this.getallGas()" :key="index" :class='[item.close?"gas-child-click":"gas-child-noclick"]' @click="closeSingleGas(item)">
        <div class="gas-child-left">
          <div class="wristband-title">
            <div>
              <div class="iconfont icon-shouhuanshezhi"></div>
              <div :style='{color: !item.online || item.close || (this.getCuTimec() - item.time2 >  this.$store.state.ipMacData.send.checkTime ) ? "red":"#FFFFFF"}'>NO.0{{item.gasid}}气体检测仪器</div>
            </div>
            <div>
              <!-- <div class="iconfont icon-dianchi"></div> -->
              <!-- <div>98%</div> -->
            </div>
          </div>
          <div class="machine-time">
            <div>数据时间：</div>
            <div>{{item.close? "-" :item.time}}</div>
          </div>
          <div class="gas-msg">
            <div class="gas-msg-con">
              <div>
                <div>
                  <div>可燃气体：</div>
                </div>
                <div>{{item.close? "-" :item.CH4}}mg/m3</div>
              </div>
              <div>
                <div>
                  <div>O2：</div>
                </div>
                <div>{{item.close? "-" :item.O2}}%</div>
              </div>
            </div>
            <div class="gas-msg-con">
              <div>
                <div>
                  <div>CO：</div>
                  <div></div>
                </div>
                <div>{{item.close? "-" :item.CO}}mg/m3</div>
              </div>
              <div>
                <div>
                  <div>H2S：</div>
                </div>
                <div>{{item.close? "-" :item.H2S}}%</div>
              </div>
            </div>
          </div>
        </div>
        <div class="gas-child-right">
          <div v-if='!item.tag' class="gas-state bulb-state-noraml">
            <div class="iconfont icon-bulb-fill"></div>
            <div>正常</div>
          </div>
          <div v-else class="gas-state bulb-state-unnoraml">
            <div class="iconfont icon-bulb-fill"></div>
            <div>异常</div>
          </div>
        </div>
      </div>
      <div class="gas-fun turn">
        <div :class='[alltag?"iconfont icon-weixian shandong":"iconfont icon-weixian"]'></div>
        <div :class='thisTime <= this.allclicktime? "turn-btn-gray":"turn-btn-red"' @click="thisTime <= this.allclicktime ?()=>{} : urgentBackAll()">紧急全部召回</div>
      </div>
      <!-- Date.now() - this.allclicktime < 60000 || Date.now() - this.allupdatetime < 60000 || Date.now() - this.groupclicktime < 5000 -->
      <div class="gas-fun turn-group">
        <div :class='thisTime <= this.allclicktime ?"trun-group-btn-gray" :"trun-group-btn-red"' @click="thisTime <= this.allclicktime ?()=>{} :urgentBackGroup(1, 5, true)">1组召回</div>
        <div :class='thisTime <= this.allclicktime?"trun-group-btn-gray" :"trun-group-btn-red"' @click="thisTime <= this.allclicktime ?()=>{} :urgentBackGroup(6, 10, true)">2组召回</div>
        <div :class='thisTime <= this.allclicktime?"trun-group-btn-gray" :"trun-group-btn-red"' @click="thisTime <= this.allclicktime ?()=>{} :urgentBackGroup(11, 15, true)">3组召回</div>
        <div :class='thisTime <= this.allclicktime?"trun-group-btn-gray" :"trun-group-btn-red"' @click="thisTime <= this.allclicktime ?()=>{} :urgentBackGroup(16, 20, true)">4组召回</div>
      </div>
    </div>
    <div class="wristband-detector">
      <div v-for="(item, index) in this.getallSh()" :key="index" :class='item.close?"wristband-click":"wristband-noclick"'>
        <div @click="closeSingleSh(item)">
          <div class="wristband-title">
            <div>
              <div class="iconfont icon-shouhuanshezhi"></div>
              <div :style='{color: item.close || !item.online || (this.getCuTimec() - item.time2 >  this.$store.state.ipMacData.send.checkTime )? "red":"#FFFFFF"}'>NO.{{item.shid}}手环</div>
            </div>
            <div v-if="true" class="battary-data">
              <div class="iconfont icon-dianchi"></div>
              <div>{{item.close || !item.online || (this.getCuTimec() - item.time2 >  this.$store.state.ipMacData.send.checkTime )? 0:item.battartquantity}}%</div>
            </div>
            <div v-else>
              <div class="wristband-none">未连接</div>
            </div>
          </div>
          <div class="machine-time">
            <div>数据时间：</div>
            <div>{{item.close || !item.online || (this.getCuTimec() - item.time2 >  this.$store.state.ipMacData.send.checkTime )?'-': item.time}}</div>
          </div>
          <div class="wristband-msg">
            <div>
              <div>心率：</div>
              <div>{{item.close || !item.online || (this.getCuTimec() - item.time2 >  this.$store.state.ipMacData.send.checkTime )?'-': item.heartrate}}</div>
            </div>
            <div>
              <div>血氧：</div>
              <div>{{item.close || !item.online || (this.getCuTimec() - item.time2 >  this.$store.state.ipMacData.send.checkTime )?'-': item.bloodoxygen}}</div>
            </div>
          </div>
          <div class="wristband-msg">
            <div>
              <div>血压 ：</div>
              <div>{{item.close || !item.online || (this.getCuTimec() - item.time2 >  this.$store.state.ipMacData.send.checkTime )?'-': item.systolic}}/{{item.close || !item.online || (this.getCuTimec() - item.time2 >  this.$store.state.ipMacData.send.checkTime )?'-': item.diastolic}}</div>
            </div>
            <div>
              <div>体温：</div>
              <div>{{item.close || !item.online || (this.getCuTimec() - item.time2 >  this.$store.state.ipMacData.send.checkTime )?'-': item.temperature}}</div>
            </div>
          </div>
        </div>
        <div class="btn-all" v-if="!item.close && item.online">
          <div @click='urgentBackSingle(item)'>召回</div>
          <div @click='setBreakSingle(item)'>刷新</div>
          <!-- <div @click='setBreakSingle(item)'>断开</div> -->
          <!-- <div @click='setShtime(item)'>校时</div> -->
        </div>
      </div>
    </div>
    <div class="dialog-right" id ="dialog-right">
    </div>
    <div class="dialog-left" id ="dialog-left">
    </div>
    <div class="closebtn">
      <div class="closebtn-btn-other" @click="closeBtn()">关闭</div>
      <div class="closebtn-btn-other" @click="setBtn()">设置</div>
      <div class="closebtn-btn-other" @click="setBreakAll2(0)">全部刷新</div>
      <div :class='thisTime <= this.allclicktime ? "closebtn-btn-gray":"closebtn-btn-red"' @click="thisTime <= this.allclicktime ?()=>{} :setShAlltime()">全部校时</div>
      <!-- <div @click="clearStroge()">清理缓存</div> -->
    </div>
    <div class="setPage" v-if="setPage">
      <SetPageVue></SetPageVue>
    </div>
</div>
</template>

<script>
const dgram = require("dgram")
const path = require("path")
import { analyseDataSh, analyseDataGas, ab2hex, hex2int, toHexStr, dec2hex, getNumLenght } from "./../ex16hex.js"
import SetPageVue from'@/components/SetPage.vue'
import logger from "@/log"  

const ipcRenderer = require('electron').ipcRenderer
export default {
  name: 'HomeView',
  components:{
    SetPageVue
  },
  data() {
    return {
      audio: null,
      ipData: [],
      orderData: [],

      shdata:[],
      qtdata: [],

      alltag: false,
      iperror: false,
      dialogshow: "",
      setPage: false,
      allclicktime: Date.now(),
      thisTime:Date.now()
    };
  },
  watch:{
  },
  created() {
    this.fristFun()
    this.init()
    // this.setDataZero()
  },
  mounted(){
    this.audio = new Audio()
    this.audio.src = path.join(__static, "/baojing.mp3").replaceAll(".asar", "")

    this.server = null
    this.server = dgram.createSocket("udp4")
    this.connect()
    setInterval(()=>{
      this.thisTime = Date.now()
    }, 1000)
  },
  updated() {
  },
  methods:{
    logFun(info){
      logger.info(info)
    },
    clearStroge(){
      window.localStorage.clear()
    },
    // 第一个获取默认配置
    fristFun() {
      if(!this.$store.state.fristOpen) {
        // 第一次开机
        this.$store.commit("changeIpMacData", JSON.parse(JSON.stringify(require("./../ip.json"))))
        this.$store.commit("changeOrderData", JSON.parse(JSON.stringify(require("./../order.json"))))
        this.$store.commit("changeFristOpen", true)
        console.log("第1次打开"+ this.$store.state.ipMacData)
      } else {
        console.log("第2次打开"+ this.$store.state.ipMacData)
      }
    },
    // udp4连接
    connect() {
      this.server.on("message",(msg,rinfo)=>{
        let mt = ab2hex(msg)
        let part = mt.slice(0, 4)
        this.checkNetWall(mt)
       
        if(msg.byteLength == 188) {
          console.log(6)
          let mac = mt.slice(26, 38)
          let jsonString = Buffer.from(msg).toString('utf8')
          jsonString = jsonString.slice(0, jsonString.length - 1)
          let index = jsonString.indexOf("{")
          jsonString = jsonString.slice(index, jsonString.length)

          try{
            const parsedData = JSON.parse(jsonString)
            this.addGas(analyseDataGas(mac, parsedData.data))
          }catch(e){

          }
        } else if(part.indexOf("adba") != -1) {
          let shNum = mt.slice(34, 38)
          let rawData = mt.slice(38, mt.length-4)
          this.addShouhuan(analyseDataSh(rawData, rawData.length / hex2int(shNum)))
        } else if(part.indexOf("acca") != -1){
          let msgOk =  this.$store.state.orderData.shOrder.msgOk.replaceAll(" ", "").toString().toLowerCase()
          let timeOk =  this.$store.state.orderData.shOrder.timeOk.replaceAll(" ", "").toString().toLowerCase()

          // console.log(mt, msgOk)
          // console.log(mt, timeOk)
          let allsh = this.getallSh()

          if(mt.indexOf(msgOk) != -1) {
            for (var a in allsh){
              let sh = allsh[a]
              let shmac = this.changeMac(sh.shmac)
              let shid = sh.shid

              if(mt.indexOf(shmac) != -1) {
                this.showShMsgOkBack(shid, shmac, "收到消息", false)
                console.log("------>接收到召回" + shid)
              }
            }
          }
          if(mt.indexOf(timeOk) != -1) {
            for (var a in allsh){
              let sh = allsh[a]
              let shmac = this.changeMac(sh.shmac)
              let shid = sh.shid

              if(mt.indexOf(shmac) != -1) {
                this.showShMsgOkBack(shid, shmac, "时间设置", true)
                console.log("-->接收到时间" + shid)
              }
            }
          }
        }
      });
      
      this.server.on("listening",()=>{
          let adress = this.server.address();
          console.log("服务器监听："+adress.adress+":"+adress.port);

          this.setBreakAll2(0)

          // 获取当前蓝牙地址
          setInterval(()=>{
            this.sendMsg("", "ACCA 000E FFFFFFFFFFFF 0003 E1 CC", false, 'qiti')
          }, 1000)

          // 定时刷新气体检测仪验证
          setInterval(()=>{
            for (var a in this.getallGas()){
              let child1 = this.getallGas()[a]
              if(!child1.close) {
                let mac1 = child1.gasmac.replaceAll(':', ' ').toUpperCase()
                this.sendMsg(mac1, this.$store.state.orderData.gasOrder.vertifypre + " " + mac1 + " " + this.$store.state.orderData.gasOrder.vertifybac, false, 'qiti')
              }
            }
          }, 3000)

          setInterval(()=>{
            for (var a in this.getallGas()){
              let child1 = this.getallGas()[a]
              if(!child1.close){
                let mac2 = child1.gasmac.replaceAll(':', ' ').toUpperCase()
                // console.log("气体2")
                this.sendMsg(mac2, this.$store.state.orderData.gasOrder.gatherpre  + " " + mac2 + " " + this.$store.state.orderData.gasOrder.gatherbac, false, 'qiti')
              }
            }
            setTimeout(()=>{
              for (var a in this.getallGas()){
                let child3 = this.getallGas()[a]
                if(!child3.close){
                  let mac3 = child3.gasmac.replaceAll(':', ' ').toUpperCase()
                  // console.log("气体2")
                  this.sendMsg(mac3, this.$store.state.orderData.gasOrder.gatherpre  + " " + mac3 + " " + this.$store.state.orderData.gasOrder.gatherbac, false, 'qiti')
                }
              }
            }, 1000)
          }, 2000)
      });
      
      this.server.on("error",(err)=>{
        console.log("服务器异常错误："+err.message);
        this.iperror = true
      });
      
      this.server.bind(this.$store.state.ipMacData.self.macport, this.$store.state.ipMacData.self.netip);
      // 注册发送事件
      this.server.addListener("sendEv", (mac,msg, all,who)=>{
        for (var a in this.$store.state.ipMacData.other){
          let hostip = this.$store.state.ipMacData.other[a]
          var hex = msg
          var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
            return parseInt(h, 16)
          }))
          this.server.send(typedArray, hostip.macport, hostip.netip)
        }
      })
    },
    sendMsg(mac,msg,all, who) {
      // console.log("--->>", msg)
      this.server.emit("sendEv", mac,msg, all, who);
    },
    setBtn() {
      this.setPage = true
    },
    clseSetBtn(){
      this.setPage = false
    },
    closeBtn(){
      ipcRenderer.send('close')
    },
    getShandong(){
      this.qtdata = this.getallGas()
      for (var a in this.qtdata){
        if(this.qtdata[a].tag) {
          this.playVideo()
          this.alltag = true
          return
        }
      }
      this.stopVideo()
      this.alltag = false
    },
    playVideo() {
      this.audio.play()
    },
    // 播放警报声音
    playDuanwang() {
      this.audio.src = path.join(__static, "/baojing.mp3").replaceAll(".asar", "")
      this.audio.play()
    },
    // 暂停声音
    stopVideo() {
      this.audio.pause()
    },
    // 关闭某个手环
    closeSingleSh(item) {
      item.close = !item.close
      console.log(item.close)
    },
    // 关闭某个气体检测仪器
    closeSingleGas(item){
      item.close = !item.close
    },
    // 全部召回
    urgentBackAll(){

      let timegroup1 = this.sumGroupMsgTime(1, 5, 3)
      let timegroup2 = this.sumGroupMsgTime(6, 10, 3)
      let timegroup3 = this.sumGroupMsgTime(11, 15, 3)
      let timegroup4 = this.sumGroupMsgTime(16, 20, 3)

      let timeadd = timegroup1 + timegroup2 + timegroup3 + timegroup4+ this.$store.state.ipMacData.send.groupsendtimegap*3
      this.allclicktime = Date.now() + timeadd
      console.log("全部召回", timeadd)

      this.urgentBackGroup(1, 5, false)
      setTimeout (()=>{
        this.urgentBackGroup(6, 10, false)
      }, timegroup1 + this.$store.state.ipMacData.send.groupsendtimegap)
      setTimeout (()=>{
        this.urgentBackGroup(11, 15, false)
      }, timegroup1 + timegroup2 + this.$store.state.ipMacData.send.groupsendtimegap* 2)
      setTimeout (()=>{
        this.urgentBackGroup(16, 20,false)
      }, timegroup1 + timegroup2 + timegroup3+ this.$store.state.ipMacData.send.groupsendtimegap*3)
    },
    urgentBackGroup(min, max, bo){
     
      // 建立连接
      let index = max/5 - 1

      let order = this.$store.state.orderData.shOrder
      let allsh = this.getallSh()
      let b = ""
      let resultJson = []
      for (var a in allsh){
        let child = allsh[a]
        let id = child.shid
        let mac1 = child.shmac.replaceAll(':', ' ').toUpperCase()
        if(child.online && !child.close && id <= max && id >=min){
          child.online = false
          b += (id + " ")
          resultJson.push(child)
        }
      }

      console.log("一组召回" + min + "-" + max, "为 " + b)
      if(bo) {
        let timeadd = this.$store.state.ipMacData.send.singlesendtimegap * resultJson.length * 3
        this.allclicktime = Date.now() + timeadd
        console.log("一组找回间隔时间 ", timeadd)
      }
      if(resultJson.length == 0)  return

      let resultPre = this.mergePreSh(resultJson)
      this.sendMsg("", resultPre, true, 'shouhuan')

      setTimeout(() => {
        let resultMsg = this.mergeMsgSh(resultJson)
        this.sendMsg("", resultMsg, true, 'shouhuan')
        setTimeout(()=>{
          let resultAdd = this.mergeAddSh(resultJson)
          this.sendMsg("", resultAdd, true, 'shouhuan')
          setTimeout(() => {
            let resultBreak = this.mergeBreakSh(resultJson)
            this.sendMsg("", resultBreak, true, 'shouhuan')
          }, this.$store.state.ipMacData.send.singlesendtimegap * resultJson.length);
        }, this.$store.state.ipMacData.send.singlesendtimegap * resultJson.length)
      }, this.$store.state.ipMacData.send.singlesendtimegap * resultJson.length);
    },
    //按时间召回一组
    sumGroupTimeTime(min,max, int) {
      let allsh = this.getallSh()
      let b = 0
      for (var a in allsh){
        let child = allsh[a]
        let id = child.shid
        if(child.online && id <= max && id >=min){
          b ++ 
        }
      }

      return b * this.$store.state.ipMacData.send.singleClicktimegap * int
    },
    //按时间发送一组消息
    sumGroupMsgTime(min,max, int) {
      let allsh = this.getallSh()
      let b = 0
      for (var a in allsh){
        let child = allsh[a]
        let id = child.shid
        if(child.online && id <= max && id >=min){
          b ++ 
        }
      }

      return b * this.$store.state.ipMacData.send.singlesendtimegap * int
    },
    //生成手环验证命令
    mergePreSh(data){
      let preoder = "AC CA" + " WW WW" + " FF FF FF FF FF FF" + " 00 03 10" + " " + dec2hex(data.length, 2)
      for (var a in data){
        let child = data[a]
        let mac1 = child.shmac.replaceAll(':', ' ').toUpperCase()
        preoder += " " + mac1
      }

                // 00 00 01 00 01 00 10 CC     00 00 01 00 10 00 11 CC"
      preoder += " 00 00 00 CC "
      let temp = preoder.replaceAll(" ", "")
      let alllenght = dec2hex(temp.length / 2, 4)
      preoder= preoder.replace("WW WW", alllenght)
      console.log(preoder)
      return preoder
    },
     //生成手环消息命令
    mergeMsgSh(data){
      let preoder = "AC CA" + " WW WW" + " FF FF FF FF FF FF" + " 00 03 12" + " " + dec2hex(data.length, 2)
      for (var a in data){
        let child = data[a]
        let mac1 = child.shmac.replaceAll(':', ' ').toUpperCase()
        preoder += " " + mac1
      }

      preoder += " 00 0E 01 0D A0 04 0B 00 08 4F 60 59 7D 54 17 FF 1F CC "
      let temp = preoder.replaceAll(" ", "")
      let alllenght = dec2hex(temp.length / 2, 4)
      preoder= preoder.replace("WW WW", alllenght)
      console.log(preoder)
      return preoder
    },
    //生成手环追加命令
    mergeAddSh(data){
      let preoder = "AC CA" + " WW WW" + " FF FF FF FF FF FF" + " 00 03 12" + " " + dec2hex(data.length, 2)
      for (var a in data){
        let child = data[a]
        let mac1 = child.shmac.replaceAll(':', ' ').toUpperCase()
        preoder += " " + mac1
      }

      preoder += " 00 0E 01 04 A0 04 0B FF CC "
      let temp = preoder.replaceAll(" ", "")
      let alllenght = dec2hex(temp.length / 2, 4)
      preoder= preoder.replace("WW WW", alllenght)
      console.log(preoder)
      return preoder
    },
    //生成手环断开命令
    mergeBreakSh(data){
      let preoder = "AC CA" + " WW WW" + " FF FF FF FF FF FF" + " 00 03 11" + " " + dec2hex(data.length, 2)
      for (var a in data){
        let child = data[a]
        let mac1 = child.shmac.replaceAll(':', ' ').toUpperCase()
        preoder += " " + mac1
      }

      preoder += " CC "
      let temp = preoder.replaceAll(" ", "")
      let alllenght = dec2hex(temp.length / 2, 4)
      preoder= preoder.replace("WW WW", alllenght)
      console.log(preoder)
      return preoder
    },
    //生成手环校验时间命令
    mergeTimeSh(data){
      let preoder = "AC CA" + " WW WW" + " FF FF FF FF FF FF" + " 00 03 12" + " " + dec2hex(data.length, 2)
      for (var a in data){
        let child = data[a]
        let mac1 = child.shmac.replaceAll(':', ' ').toUpperCase()
        preoder += " " + mac1
      }

      preoder += " 00 0E 01 0A A0 02 01 "+ toHexStr()+ " CC "
      let temp = preoder.replaceAll(" ", "")
      let alllenght = dec2hex(temp.length / 2, 4)
      preoder= preoder.replace("WW WW", alllenght)
      console.log(preoder)
      return preoder
    },
    //单个召回
    urgentBackSingle(item){
      console.log("单个召回 ", item.shid )
      let allsh = this.getallSh()
      let resultJson = []
      for (var a in allsh){
        let child = allsh[a]
        if(child.online && !child.close && item.shid == child.shid){
          child.online = false
          resultJson.push(child)
        }
      }
      if(resultJson.length == 0) return
      let resultPre = this.mergePreSh(resultJson)
      this.sendMsg("", resultPre, true, 'shouhuan')

      setTimeout(() => {
        let resultMsg = this.mergeMsgSh(resultJson)
        this.sendMsg("", resultMsg, true, 'shouhuan')
        setTimeout(()=>{
          let resultAdd = this.mergeAddSh(resultJson)
          this.sendMsg("", resultAdd, true, 'shouhuan')
          setTimeout(() => {
            let resultBreak = this.mergeBreakSh(resultJson)
            this.sendMsg("", resultBreak, true, 'shouhuan')
          }, 1000);
        }, 1000)
      }, 1000);
    },
    // 检查网关
    checkNetWall(mt) {
      for (var a in this.$store.state.ipMacData.other){
        let macc = this.changeMac(this.$store.state.ipMacData.other[a].bifimac)

        this.$store.state.ipMacData.other[a].online = false
        if(mt.indexOf(macc) != -1) {
          this.$store.state.ipMacData.other[a].online = true
          clearTimeout(this.$store.state.ipMacData.other[a].timeclick)
          this.$store.state.ipMacData.other[a].timeclick =  setTimeout(()=>{
            this.$store.state.ipMacData.other[a].online= false
          }, this.$store.state.ipMacData.send.checkTime)
        }
      }
    },
    // 在界面显示手环接受消息命令闭环
    showShMsgOkBack(id, mac, nsg, bb) {
      let dialogright = document.getElementById("dialog-right")
      let child = document.createElement("div")
      child.innerText = "手环No." + id + nsg + "\n"
      child.style.fontSize= '40px'
      dialogright.appendChild(child)
      setTimeout(()=>{
        dialogright.removeChild(child)
        if(bb) {
          let order = this.$store.state.orderData.shOrder
          this.sendMsg(mac, order.breaklanyapre+" " + mac + " " + order.breaklanyabac, true, 'shouhuan')
        }
      }, 4000)
    },
    // 在界面显示发送某个手环召回命令
    showZhaohui(id) {
      let dialogleft = document.getElementById("dialog-left")
      let child = document.createElement("div")
      child.innerText = "手环No." + id + "发送召回\n"
      child.style.fontSize= '40px'
      dialogleft.appendChild(child)
      setTimeout(()=>{
        dialogleft.removeChild(child)
      }, 2000)
    },
    // 所有手环校验时间
    setShAlltime() {
      let timegroup1 = this.sumGroupTimeTime(1, 5, 3)
      let timegroup2 = this.sumGroupTimeTime(6, 10, 3)
      let timegroup3 = this.sumGroupTimeTime(11, 15, 3)
      let timegroup4 = this.sumGroupTimeTime(16, 20, 3)

      let timeadd = timegroup1 + timegroup2 + timegroup3 + timegroup4
      this.allclicktime = Date.now() + timeadd
      console.log("全部校时 ", timeadd)

      this.setGroupTime(1, 5)
      setTimeout (()=>{
        this.setGroupTime(6, 10)
      }, timegroup1)
      setTimeout (()=>{
        this.setGroupTime(11, 15)
      }, timegroup1 + timegroup2)
      setTimeout (()=>{
        this.setGroupTime(16, 20)
      }, timegroup1 + timegroup2 + timegroup3)
    },
    // 单组手环校验时间
    setGroupTime(min, max) {
      let index = max/5 - 1
    

      let allsh = this.getallSh()
      let b = ""
      let resultJson = []
      for (var a in allsh){
        let child = allsh[a]
        let id = child.shid
        let mac1 = child.shmac.replaceAll(':', ' ').toUpperCase()
        if(child.online && !child.close && id <= max && id >=min){
          child.online = false
          resultJson.push(child)

          b += (id + " ")
        }
      }

      this.allclicktime = Date.now() + this.$store.state.ipMacData.send.singleClicktimegap * resultJson.length * 2

      if(resultJson.length == 0)  return

      console.log("一组校时" + min + "-" + max, "为 " + b)
      let resultMsg = this.mergePreSh(resultJson)
      this.sendMsg("", resultMsg, true, 'shouhuan')
      setTimeout(()=>{
        let resultAdd = this.mergeTimeSh(resultJson)
        this.sendMsg("", resultAdd, true, 'shouhuan')

        setTimeout(() => {
          let resultBreak = this.mergeBreakSh(resultJson)
          this.sendMsg("", resultBreak, true, 'shouhuan')
        }, this.$store.state.ipMacData.send.singleClicktimegap * resultJson.length);
      },  this.$store.state.ipMacData.send.singleClicktimegap * resultJson.length)
    },
    // 发送断开某个手环
    setBreakSingle(item){
      this.shdata = this.getallSh()
      // toHexStr()
      let b = 0
      for (var a in this.shdata){
        let child = this.shdata[a]
        let id = child.shid
        let mac = child.shmac.replaceAll(":", " ")
        if(id == item.shid) {
          let order = this.$store.state.orderData.shOrder
          console.log("发送断开" + id)
          this.sendMsg(mac, order.breaklanyapre+" " + mac + " " + order.breaklanyabac, true, 'shouhuan')
        }
      }
    },
    // 发送断开所有手环
    setBreakAll() {
      this.shdata = this.getallSh()
      // toHexStr()
      let b = 0
      for (var a in this.shdata){
        let child = this.shdata[a]
        let id = child.shid
        let mac = child.shmac.replaceAll(":", " ")
        if(true) {
          let order = this.$store.state.orderData.shOrder
          console.log("发送断开" + id)
          // // 验证时间的时候把所有的都断开一边
          setTimeout(()=>{
            this.sendMsg(mac, order.breaklanyapre+" " + mac + " " + order.breaklanyabac, true, 'shouhuan')
          }, this.$store.state.ipMacData.send.singletimegap* b)
        }
      }
    },
    // 发送断开所有手环
    setBreakAll2(time){
      setTimeout(()=>{
        console.log("全部断开")
        this.sendMsg("", "AC CA 00 0F FF FF FF FF FF FF 00 03 11 FF CC", "")
      }, time)
    },
    // 将分析过原始数据的手环消息解析之后添加到数组
    addShouhuan(data) {
      this.shdata = this.getallSh()
      for (var b in data){
        let child2 = data[b]
        for (var a in this.shdata) {
          let child1 = this.shdata[a]
          if(this.changeMac(child1.shmac) == this.changeMac(child2.mac)) {
            this.shdata[a] = Object.assign(this.shdata[a], child2)
            this.shdata[a].time = this.getCuTime()
            clearTimeout(this.shdata[a].timeclick)
            this.shdata[a].timeclick =  setTimeout(()=>{
              this.shdata[a].online= false
              this.shdata[a].step= '-'
              this.shdata[a].heartrate= '-'
              this.shdata[a].systolic= '-'
              this.shdata[a].diastolic= '-'
              this.shdata[a].battartquantity= '-'
              this.shdata[a].sos= '-'
              this.shdata[a].key= '-'
              this.shdata[a].temperature= '-'
              this.shdata[a].sleeptime= '-'
              this.shdata[a].bloodoxygen= '-'
              clearTimeout(this.shdata[a].timeclick)
            }, this.$store.state.ipMacData.send.checkTime)
          }
        }
      }
      this.shdata.sort(this.sortFun)

      this.$forceUpdate()
    },
    // 排序规则
    sortFun (a, b){
      return a.id-b.id;
    },
    // 将分析过原始数据的气体消息解析之后添加到数组
    addGas(data) {
      this.qtdata = this.getallGas()
      for (var a in this.qtdata){
        let child = this.qtdata[a]
        if(this.changeMac(child.gasmac) == this.changeMac(data.mac)) {
          this.qtdata[a] = Object.assign(this.qtdata[a], data)
          this.qtdata[a].time = this.getCuTime()
          clearTimeout(this.qtdata[a].timeclick)
          this.qtdata[a].timeclick =  setTimeout(()=>{
            this.qtdata[a].online= false
            this.qtdata[a].CH4 = "-"
            this.qtdata[a].O2 = "-"
            this.qtdata[a].H2S = "-"
            this.qtdata[a].CO = "-"
            clearTimeout(this.qtdata[a].timeclick)
          }, this.$store.state.ipMacData.send.checkTime)
        }
      }
      this.qtdata.sort(this.sortFun)

      for (var a in this.qtdata) {
        let tt = this.qtdata[a]
        let c = false 
        // console.log("---> CH4 ", parseFloat(tt["CH4"]), parseFloat(this.getTheValueMin("CH4")), parseFloat(this.getTheValueMax("CH4")))
        // console.log("---> CO ", parseFloat(tt["CO"]), parseFloat(this.getTheValueMin("CO")), parseFloat(this.getTheValueMax("CO")))
        // console.log("---> O2 ", parseFloat(tt["O2"]), parseFloat(this.getTheValueMin("O2")), parseFloat(this.getTheValueMax("O2")))
        // console.log("---> H2S ", parseFloat(tt["H2S"]), parseFloat(this.getTheValueMin("H2S")), parseFloat(this.getTheValueMax("H2S")))

        let ch4 = parseFloat(tt["CH4"])
        let ch4Min = parseFloat(this.getTheValueMin("CH4"))
        let ch4Max = parseFloat(this.getTheValueMax("CH4"))

        if(ch4 != NaN && (ch4 > ch4Max)) {
          c = true
        }

        let CO = parseFloat(tt["CO"])
        let COMin = parseFloat(this.getTheValueMin("CO"))
        let COMax = parseFloat(this.getTheValueMax("CO"))

        if(CO != NaN && (CO > COMax)) {
          c = true
        }

        let O2 = parseFloat(tt["O2"])
        let O2Min = parseFloat(this.getTheValueMin("O2"))
        let O2Max = parseFloat(this.getTheValueMax("O2"))
        if(O2 != NaN && (O2 < O2Min)) {
          c = true
        }

        let H2S = parseFloat(tt["H2S"])
        let H2SMin = parseFloat(this.getTheValueMin("H2S"))
        let H2SMax = parseFloat(this.getTheValueMax("H2S"))

        if(H2S != NaN && (H2S > H2SMax)) {
          c = true
        }

        this.qtdata[a].tag = c
      }
      
      this.getShandong()
    },
    getCuTime() {
      return new Date().toString().split(' ')[4]
    },
    getCuTimec() {
      return new Date().getTime()
    },
    // 通过配置文件获取所有手环
    getallSh() {
      let result = []
      for (var a in this.$store.state.ipMacData.other) {
        let temp = this.$store.state.ipMacData.other[a]
        for (var b in temp.netSh) {
          let child = temp.netSh[b]
          result.push(child)
        }
      }
      return result
    },
    // 通过配置文件获取所有气体
    getallGas() {
      let result = []
      for (var a in this.$store.state.ipMacData.other) {
        let temp = this.$store.state.ipMacData.other[a]
        for (var b in temp.netGas) {
          let child = temp.netGas[b]
          if(child.gasmac){
            result.push(child)
          }
        }
      }
      return result
    },
    getAllIPPort() {
      return this.$store.state.ipMacData.other
    },
    // 根据port获取手环Mac地址
    getIpPortByMac(mac) {
      for (var a in this.$store.state.ipMacData.other) {
        let temp = this.$store.state.ipMacData.other[a]
        for (var b in temp.netSh) {
          let child = temp.netSh[b]
          if(this.changeMac(child.shmac) == this.changeMac(mac)) {
            return temp
          }
        }
      }
      for (var a in this.$store.state.ipMacData.other) {
        let temp = this.$store.state.ipMacData.other[a]
        for (var b in temp.netGas) {
          let child = temp.netGas[b]
          if(this.changeMac(child.gasmac) == this.changeMac(mac)) {
            return temp
          }
        }
      }
    },
    // 根据IP地址获取手环
    getShByMac(mac){
      for (var a in this.$store.state.ipMacData.other) {
        let temp = this.$store.state.ipMacData.other[a]
        for (var b in temp.netSh) {
          let child = temp.netSh[b]
          if(this.changeMac(child.shmac) == this.changeMac(mac)) {
            return temp
          }
        }
      }
    },
    // 根据ID地址获取手环
    getShById(id){
      for (var a in this.$store.state.ipMacData.other) {
        let temp = this.$store.state.ipMacData.other[a]
        for (var b in temp.netSh) {
          let child = temp.netSh[b]
          if(child.id == id) {
            return true
          }
        }
      }

      return true
    },
    // 根据port地址获取气体mac
    getGasMacById(id) {
      for (var a in this.$store.state.ipMacData.other) {
        let temp = this.$store.state.ipMacData.other[a]
        for (var b in temp.netGas) {
          let child = temp.netGas[b]
          if(child.gasid == id){
            return child.gasmac
          }
        }
      }
    },
    // 获取气体检测最大值
    getTheValueMax(label) {
      for (var a in this.$store.state.ipMacData.gasthreshold) {
        let temp = this.$store.state.ipMacData.gasthreshold[a]
        if(temp.label == label) {
          return temp.valueMax
        }
      }
    },
    // 获取气体检测最小值
    getTheValueMin(label) {
      for (var a in this.$store.state.ipMacData.gasthreshold) {
        let temp = this.$store.state.ipMacData.gasthreshold[a]
        if(temp.label == label) {
          return temp.valueMin
        }
      }
    },
    changeMac(mac) {
      return mac.replaceAll(':', '').replaceAll(' ', '').toLowerCase()
    },
    scoketClose() {
      this.server.close()
    },
    // 初始换页面默认数据和格式
    init() {
      this.qtdata = this.getallGas()
      for (var a in this.qtdata){
        this.qtdata[a].online= false
        this.qtdata[a].close= true
        this.qtdata[a].CH4 = "-"
        this.qtdata[a].O2 = "-"
        this.qtdata[a].H2S = "-"
        this.qtdata[a].CO = "-"
      }

      this.shdata = this.getallSh()
      for (var a in this.shdata) {
        this.shdata[a].online= false
        this.shdata[a].close= true
        this.shdata[a].step= '-'
        this.shdata[a].heartrate= '-'
        this.shdata[a].systolic= '-'
        this.shdata[a].diastolic= '-'
        this.shdata[a].battartquantity= '-'
        this.shdata[a].sos= '-'
        this.shdata[a].key= '-'
        this.shdata[a].temperature= '-'
        this.shdata[a].sleeptime= '-'
        this.shdata[a].bloodoxygen= '-'
      }

      for (var a in this.$store.state.ipMacData.other){
        this.$store.state.ipMacData.other[a].online = false
      }
    }
  },
  onUnmounted() {
    this.server.close()
    console.log("close")
  }
}
</script>

<style scoped>
.title{

}
.btn-all{
  display: flex;
  justify-content: space-between;
  color: #FFFFFF;
}
.btn-all>div{
  background: red;
  padding: 2px;
  border-radius: 2px;
}
.btn-all>div:active{
  color: rgba(6, 17, 27, 1);
}
.title-btn{
  height: 30px;
  width: 200px;
  background: red;
}
.home{
  padding: 20px;
}
.home-title{
  font-size: 34px;
  text-align: center;
  color: #FFFFFF;
}
.home-label, .home-label >div{
  font-size: 20px;
  text-align: center;
  color: #FFFFFF;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.home-label-netwall>div{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-right: 20px;
}
.home-light{
  width:26px;
  height:26px;
  border-radius: 13px;
  margin-left: 10px;
}
.gas-detector{
  display: grid;
  grid-template-columns: 3fr 3fr 180px 180px;
  grid-template-rows: 190px;
  row-gap: 10px;
  column-gap: 10px;

  margin-top: 15px;
  margin-bottom: 20px;
}
.gas-child-noclick{
  background-color: rgba(10, 29, 44, 1);
  border-radius: 10px;
  padding: 12px;
  font-size: 20px;

  display:flex;

  justify-content: space-between;
}
.gas-child-click{
  background-color: rgba(20, 20, 20, 1);
  border-radius: 10px;
  padding: 12px;
  font-size: 20px;

  display:flex;

  justify-content: space-between;
}
.gas-child-right{
  display: flex;
  justify-content: center;
  align-items: center;
}
.machine-time{
  display: flex;
  justify-content: flex-start;
}
.machine-time>div:first-child{
  width: 100px;
  color: #afffaf;
}
.machine-time>div:last-child{
  color: #FFFFFF;
}
.gas-msg{
  display: flex;
  justify-content: space-between;
  width: 90%;
}
.gas-msg-con{
  display: grid;
}
.gas-msg-con>div{
  color: rgba(200, 217, 237, 1);
  display: flex;
  justify-content: flex-start;
  width: 250px;
  
}
.gas-msg-con>div>div:first-child{
  width: 100px;
  text-align: right;
  display: inline;
  color: #afffaf;
}
.gas-msg-con>div>div>div:last-child{
  color: #afffaf;
}
.gas-msg-con>div>div{
  display: flex;
}
.gas-state{
  text-align: center;
}

.gas-fun{
  background-color: rgba(10, 29, 44, 1);
  border-radius: 10px;
  padding: 12px;
}
.turn{
  text-align: center;
}
.turn-btn-red{
  display: inline-block;
  width: 100%;
  height: 40px;
  line-height: 40px;
  color: rgba(200, 217, 237, 1);
  border-radius: 4px;
  background-color: red;
}
.turn-btn-gray{
  display: inline-block;
  width: 100%;
  height: 40px;
  line-height: 40px;
  color: rgba(200, 217, 237, 1);
  border-radius: 4px;
  background-color: gray;
}
.turn-btn-red:hover{
  background-color: burlywood;
}
.turn-group{
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1f);
  padding: 12px;
  row-gap: 5px;
  column-gap: 5px;
}
.trun-group-btn-red{
  color: #ffffff;
  background: red;
  text-align: center;
  line-height: 82px;
}
.trun-group-btn-gray{
  color: #ffffff;
  background: gray;
  text-align: center;
  line-height: 82px;
}
.trun-group-btn-red:active{
  background-color: burlywood;
}
.wristband-detector{
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-template-rows: repeat(4, 170px);
  row-gap: 10px;
  column-gap: 10px;
}
.wristband-noclick{
  background-color: rgba(10, 29, 44, 1);
  border-radius: 10px;
  padding: 12px;
  font-size: 20px
}
.wristband-click{
  background-color: rgba(20, 20, 20, 1);
  border-radius: 10px;
  padding: 12px;
  font-size: 20px
}

.wristband-title{
  display: flex;
  justify-content: space-between;
  width: 90%;
}

.wristband-title>div:first-child{
  color: rgba(200, 217, 237, 1);
  display: flex;
  align-items: center;
}
.wristband-title>div:last-child{
  width: 60px;
  color: #ffffff;
  display: flex;
  align-items: center;
}
.wristband-title>div:first-child>div:first-child{
  font-size: 34px;
  color: blue;
}
.wristband-title>div:last-child>div:first-child{
  font-size: 20px;
  color: #afffaf;
}
.wristband-msg{
  display: flex;
  justify-content: flex-start;
}
.wristband-msg > div:first-child{
  margin-bottom: 2px;
}
.wristband-msg > div > div:first-child {
  color: #afffaf;
  width: 80px;
}
.wristband-msg > div > div:last-child {
  color: #ffffff;
}
.wristband-msg> div{
  width: 50%;
  display: flex;
}

.wristband-none{
  height: 25px;
  width: 60px;
  background: rgb(131, 128, 128);
  border-radius: 4px;
  color: rgba(200, 217, 237, 1) !important;
  font-size: 15px !important;
  text-align: center;
  line-height: 25px;
}

.audio{
  width: 0px;
  height: 0px;
}

.dialog-left{
  position: absolute;
  top: 80px;
  left: 20px;
  color: #FFFFFF;
  width: 400px;
}
.dialog-right{
  position: absolute;
  top: 20px;
  right: 20px;
  color: #FFFFFF;
  width: 400px;
}

.closebtn{
  position: absolute;
  top: 10px;
  left: 20px;
  gap: 40px;
  display:  flex;
}
.closebtn-btn-other{
  padding: 12px;
  text-align: center;
  border-radius: 2px;
  background: red;
  color: white;
}
.closebtn-btn-other:active{
  background: rgba(6, 17, 27, 1);
}
.closebtn-btn-red{
  background: red;
  padding: 12px;
  color: white;
}
.closebtn-btn-gray{
  background: gray;
  padding: 12px;
  color: white;
}

.setPage{
  position: absolute;
  width: 100%;
  height: 1080px;
  background: rgba(10, 29, 44, 1);
  top: 0px;
  left: 0px;

  box-sizing: border-box;

  padding: 50px;
}
</style>